<?php

defined('FCORE_PATH') or define('FCORE_PATH', dirname(__FILE__));

//! Config class
class FConfig
{
	//! Base Url part of application with trailing slash
	var $baseUrl = "http://node.bethrezen.ru/threeton/";
	
	var $dbName = 'threeton';
	
	//! Users to allow admin access
	var $adminUsers = array(	
			'admin' => 'CHANGE_ME',
			'bethrezen' => '0p9o8i',
			'odmin' => 'njU8aN');
			
	//! allowed invalid login attempts
	var $adminLoginAttempts = 3;	
	
	//! Use mod_rewrite to accept SEO URLs
	var $useModRewrite = true;
	
	//! Admin email
	var $adminEmail = 'b37hr3z3n@gmail.com';
	
	/**
	 * Array of modules without '.php'. Will be searched in ./modules/MODULE_NAME/MODULE_NAME.php
	 * 
	 * Example:
	 * $modules  = array(
	 * 			'news', 'pages', 'faq'
	 * 		    );
	 */
	var $modules = array('news','pages', 'faq', 'glossary','works');
	
	//! Required libraries to include. Will be searched in ./libs/ directory in order: LIBRARY_NAME/LIBRARY_NAME.php
	var $requiredLibs = array('txt-db-api');
	
	//! Constructor
	function FConfig()
	{
	
	}
}



//! Core of our simple framework
class FCore
{	
	//! Config of core. Instance of FConfig class
	var $config;
	
	//! Modules
	var $modules = array();
	
	//! Database
	var $db;
	
	//! Admin links
	var $adminLinks = array();
	
	//! Action(module) name
	var $action = '';
	
	//! isAdminAction
	var $isAdminAction = false;
	
	//! ActionFunction name
	var $actionFunction = '';
	
	//! Constructor
	function FCore($config = null)
	{
		define('FPROTECTED_PATH', F_BASE_PATH . '/protected');
		define('DB_DIR', FPROTECTED_PATH . '/db/');
		define('API_HOME_DIR', FPROTECTED_PATH . '/libs/txt-db-api/');
		
		if ($config == null)
			$config = new FConfig();
		
		$this->config = $config;
		
		
		
		$this->parseParams();
		$this->loadLibs();
		
		if (!file_exists(DB_DIR . $this->config->dbName))
		{
			$this->db = new Database(ROOT_DATABASE);
			$this->db->executeQuery("CREATE DATABASE " . $this->config->dbName);
			
		}
		
		$this->db = new Database($this->config->dbName);
		
		$this->loadModules();	
		
		$this->act();
		
	}
	
	//! As replace for dirname($_SERVER['SCRIPT_NAME']);
	function getDirectoryName()
	{
		$dir = dirname($_SERVER['SCRIPT_NAME']);
		if (substr($dir,-1)=="/")
			return substr($dir, 0, -1);
		else
			return $dir;
	}
	
	//! Act for action
	function act()
	{
		if (isset($_GET['action']))
			$this->action = $_GET['action'];
		if (isset($_POST['action']))
			$this->action = $_POST['action'];
			
		if (isset($_GET['actAdmin']))
		{
				$this->action = $_GET['actAdmin'];
				$this->isAdminAction = true;
		}
		if (isset($_POST['actAdmin']))
		{
				$this->action = $_POST['actAdmin'];
				$this->isAdminAction = true;
		}		
		
	}
	
	
	//! Parses parameters of script
	function parseParams()
	{
		$this->normalizeRequest();
		
	}
	
	//! Strip slashes if magic_quotes are on
	function normalizeRequest()
        {
                // normalize request
                if(get_magic_quotes_gpc())
                {
                        if(isset($_GET))
                                $_GET=$this->stripSlashes($_GET);
                        if(isset($_POST))
                                $_POST=$this->stripSlashes($_POST);
                        if(isset($_REQUEST))
                                $_REQUEST=$this->stripSlashes($_REQUEST);
                        if(isset($_COOKIE))
                                $_COOKIE=$this->stripSlashes($_COOKIE);
                }
        }

        /**
         * Strips slashes from input data.
         * This method is applied when magic quotes is enabled.
         * @param mixed input data to be processed
         * @return mixed processed data
         */
        public function stripSlashes(&$data)
        {
                return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
        }

	//! Loads required libraries
	function loadLibs()
	{
		foreach ($this->config->requiredLibs as $lib)
		{
			if (file_exists(FPROTECTED_PATH . "/libs/$lib/$lib.php"))
				include(FPROTECTED_PATH . "/libs/$lib/$lib.php");
				
		}
	}
	
	//! Loads modules
	function loadModules()
	{
	
		foreach ($this->config->modules as $module)
		{
			if (file_exists(FPROTECTED_PATH . "/modules/$module/$module.php"))
			{
				include(FPROTECTED_PATH . "/modules/$module/$module.php");
				$this->modules[$module] = new $module($this);
				
			}	
		}
		
	}
	
	//! Translates RUS2Translit and make's it an URL-friendly
	function translitUrl($string)
	{
		return urlencode($this->ruslat($string));
	}
	
	//! Rus2Translit
	function ruslat ($string) 
	{
		$string = ereg_replace("ж","zh",$string);
		$string = ereg_replace("ё","yo",$string);
		$string = ereg_replace("й","i",$string);
		$string = ereg_replace("ю","yu",$string);
		$string = ereg_replace("ь","'",$string);
		$string = ereg_replace("ч","ch",$string);
		$string = ereg_replace("щ","sh",$string);
		$string = ereg_replace("ц","c",$string);
		$string = ereg_replace("у","u",$string);
		$string = ereg_replace("к","k",$string);
		$string = ereg_replace("е","e",$string);
		$string = ereg_replace("н","n",$string);
		$string = ereg_replace("г","g",$string);
		$string = ereg_replace("ш","sh",$string);
		$string = ereg_replace("з","z",$string);
		$string = ereg_replace("х","h",$string);
		$string = ereg_replace("ъ","''",$string);
		$string = ereg_replace("ф","f",$string);
		$string = ereg_replace("ы","y",$string);
		$string = ereg_replace("в","v",$string);
		$string = ereg_replace("а","a",$string);
		$string = ereg_replace("п","p",$string);
		$string = ereg_replace("р","r",$string);
		$string = ereg_replace("о","o",$string);
		$string = ereg_replace("л","l",$string);
		$string = ereg_replace("д","d",$string);
		$string = ereg_replace("э","ye",$string);
		$string = ereg_replace("я","ja",$string);
		$string = ereg_replace("с","s",$string);
		$string = ereg_replace("м","m",$string);
		$string = ereg_replace("и","i",$string);
		$string = ereg_replace("т","t",$string);
		$string = ereg_replace("б","b",$string);
		$string = ereg_replace("Ё","yo",$string);
		$string = ereg_replace("Й","I",$string);
		$string = ereg_replace("Ю","YU",$string);
		$string = ereg_replace("Ч","CH",$string);
		$string = ereg_replace("Ь","'",$string);
		$string = ereg_replace("Щ","SH'",$string);
		$string = ereg_replace("Ц","C",$string);
		$string = ereg_replace("У","U",$string);
		$string = ereg_replace("К","K",$string);
		$string = ereg_replace("Е","E",$string);
		$string = ereg_replace("Н","N",$string);
		$string = ereg_replace("Г","G",$string);
		$string = ereg_replace("Ш","SH",$string);
		$string = ereg_replace("З","Z",$string);
		$string = ereg_replace("Х","H",$string);
		$string = ereg_replace("Ъ","''",$string);
		$string = ereg_replace("Ф","F",$string);
		$string = ereg_replace("Ы","Y",$string);
		$string = ereg_replace("В","V",$string);
		$string = ereg_replace("А","A",$string);
		$string = ereg_replace("П","P",$string);
		$string = ereg_replace("Р","R",$string);
		$string = ereg_replace("О","O",$string);
		$string = ereg_replace("Л","L",$string);
		$string = ereg_replace("Д","D",$string);
		$string = ereg_replace("Ж","Zh",$string);
		$string = ereg_replace("Э","Ye",$string);
		$string = ereg_replace("Я","Ja",$string);
		$string = ereg_replace("С","S",$string);
		$string = ereg_replace("М","M",$string);
		$string = ereg_replace("И","I",$string);
		$string = ereg_replace("Т","T",$string);
		$string = ereg_replace("Б","B",$string);
		return $string;
	}
	
	
	function checkAdmin()
	{
		
		
		// start a session... we'll want to track how many times they fail logging in
		session_start();
		
		if (isset($_GET['logout'])==true)
			if ($_GET['logout'] == '1')
				if (isset($_SESSION['loggedIn']))
					unset ($_SESSION['loggedIn']);
		$logged = false;
		
		if (isset($_SESSION['loggedIn']))
			if ($_SESSION['loggedIn']==true)
				$logged = true;
				
		if ($logged == false)
		{
			if (!isset($_SERVER['PHP_AUTH_USER'])) {
				header("WWW-Authenticate: Basic realm=\"Restricted Access\"");
				header("HTTP/1.0 401 Unauthorized");
				echo "You are not authorized to access this area.";
				exit;
			}
			
			// is the username/pass valid?
			while( empty($this->config->adminUsers[$_SERVER['PHP_AUTH_USER']]) || $this->config->adminUsers[$_SERVER['PHP_AUTH_USER']] != $_SERVER['PHP_AUTH_PW'] ) {
				if( empty($_SESSION['loginCount']) || $_SESSION['loginCount'] <= $this->config->adminLoginAttempts ) {
					// invalid login... number of attempted logins is less than maximum allowed, prompt again...
					$_SESSION['loginCount']++;
					header("WWW-Authenticate: Basic realm=\"Restricted Area\"");
					exit;
				} else {
					// invalid login... number of attempted logins has reached maximum allowed, deny access...
					header("HTTP/1.0 401 Unauthorized");
					echo "You are not authorized to access this area.";
					$_SESSION['loginCount'] = 0;
					exit;
				}
			}
		
		$_SESSION['loggedIn'] = true;
		}
		
	}
	
	
	//! UTF-8 Safe substr function
	function utf8_substr($str,$from,$len)
	{
		return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
				'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
				'$1',$str);
	}
}


